import { filterRouterByParent, mapRouter } from '@/utils/filterData'
import { getUserInfo } from '@/api/sys/auth'
import { getToken } from '@/utils/token'
import router, { removeRouer } from '@/router/'
import NotFound from '@/page/error/NotFound'
import { Notification } from 'element-ui'

/** common */
const Layout = () => import(/* webpackChunkName: "group-common" */ '@/layout')

/** page */
const Home = () => import(/* webpackChunkName: "group-page" */'@/page/home')

const state = {
  menuList: [],
  websock: null
}

const mutations = {
  SET_MENU_LIST: (state, list) => {
    state.menuList = list
  },
  SET_WEBSOCKET: (state, websock) => {
    state.websock = websock
  }
}

const actions = {
  generateRoutes({ commit, dispatch }) {
    return new Promise(async (resolve) => {
      // TODO 页面刷新后 路由 userinfo重新注册
      await getUserInfo().then((res) => {
        const { menuEntityList } = res.obj
        // 清空之前用户路由
        removeRouer()
        // 设置用户信息 并 注册路由 过滤路由后生成路由菜单数组
        let menuList = mapRouter(filterRouterByParent(menuEntityList, '0'))
        commit('SET_MENU_LIST', menuList)
        dispatch('user/setUser', { userInfo: res.obj }, { root: true })
        dispatch('set_websocket')
        router.addRoutes([{
          path: '',
          component: Layout,
          children: [
            {
              path: '/Layout',
              component: Home,
              name: 'Home',
              meta: { title: '首页' }
            },
            ...menuList,
            {
              path: '*',
              component: NotFound,
              name: 'NotFound',
              meta: { title: '404' }
            }
          ]
        }])
        resolve(res.obj)
      })
    })
  },
  set_websocket({ commit, dispatch }) {
    const token = getToken().split(' ')[1]
    const websock = state.websock = new WebSocket(`${process.env.VUE_APP_WS_API}webSocket/logout${token}`)
    websock.onerror = () => {
      Notification({
        title: 'WebSocket连接发生错误',
        type: 'error',
        duration: 0
      })
    }
    websock.onmessage = (e) => {
      const data = e.data
      if (e.data === 'LOGOUT') {
        Notification({
          title: '',
          message: '你被踢了！！！',
          dangerouslyUseHTMLString: true,
          type: 'error',
          duration: 0
        })
        setTimeout(() => {
          dispatch('user/logUserout', {}, { root: true })
        }, 3000)
      }
      if (data.msgType === 'INFO') {
        Notification({
          title: '',
          message: data.msg,
          type: 'success',
          dangerouslyUseHTMLString: true,
          duration: 5500
        })
      } else if (data.msgType === 'ERROR') {
        Notification({
          title: '',
          message: data.msg,
          dangerouslyUseHTMLString: true,
          type: 'error',
          duration: 0
        })
      }
    }
    commit('SET_WEBSOCKET', websock)
  }
}

export default {
  namespaced: true,
  actions,
  state,
  mutations
}
